<template>
  <div>
    <canvas ref="canvas_character" class="canvas_character" :width="width" :height="height" @click="reset"> </canvas>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';

const width = 100;
const height = 32;
const length = 4;
const codeCharacter = ref('');

const canvas_character = ref();

// 绘制图形码
const drawCharater = () => {
  const ctx = canvas_character.value.getContext('2d');
  // this.ctx.textBaseline = 'bottom';
  ctx.fillStyle = randomColor(180, 255);
  ctx.fillRect(0, 0, width, height);

  const strLen = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789abcdefghijklmnpqrstuvwxyz';

  for (let i = 0; i < length; i++) {
    let txt = strLen[randomNum(0, strLen.length)];

    // 随机生成字体颜色
    ctx.fillStyle = randomColor(1, 100);
    // 随机生成字体大小(0.5 - 0.75)高的范围
    // ctx.font = randomNum((height * 2) / 4, (height * 3) / 4) + 'px SimHei';
    // 字体对齐位置
    // ctx.textBaseline = 'top';
    ctx.font = 'bold 30px serif';

    // 设置字体垂直方向的对齐方式
    ctx.textBaseline = 'top';

    let x = (i + 0.2) * (width / length);
    // let y = randomNum(5, height / 4);
    // let deg = randomNum(-45, 45);
    ctx.translate(x, 0);
    // ctx.rotate((deg * Math.PI) / 180);
    ctx.fillText(txt, 0, 0);
    // // 恢复坐标原点和旋转角度
    // ctx.rotate((-deg * Math.PI) / 180);
    ctx.translate(-x, 0);

    // 保存生成的字符串
    codeCharacter.value += txt;
  }
  // 绘制干扰线
  for (let j = 0; j < 10; j++) {
    ctx.strokeStyle = randomColor(40, 180);
    ctx.beginPath();
    ctx.moveTo(randomNum(0, width), randomNum(0, height));
    ctx.lineTo(randomNum(0, width), randomNum(0, height));
    ctx.stroke();
  }
  // 绘制干扰点
  // for (let k = 0; k < 30; k++) {
  //   ctx.fillStyle = randomColor(0, 255);
  //   ctx.beginPath();
  //   ctx.arc(randomNum(0, width), randomNum(0, height), 1, 0, 2 * Math.PI);
  //   ctx.fill();
  // }
};
const randomColor = (min: number, max: number) => {
  let r = randomNum(min, max);
  let g = randomNum(min, max);
  let b = randomNum(min, max);
  return 'rgb(' + r + ',' + g + ',' + b + ')';
};
const randomNum = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min) + min);
};
const reset = () => {
  drawCharater();
};

onMounted(() => {
  drawCharater();
});
</script>

<style scoped></style>
